package it.netsphere.nswing.comp;

import it.netsphere.nswing.IIntegerIdentifier;

import java.awt.Component;

import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.ListCellRenderer;
import javax.swing.SwingConstants;

import ognl.Ognl;
import ognl.OgnlContext;
import ognl.OgnlException;

@SuppressWarnings("rawtypes")
public class NSComboBoxRenderer extends JLabel implements ListCellRenderer {

    private String expression;

    private static final long serialVersionUID = 8301922619435271091L;

    public NSComboBoxRenderer() {
        setOpaque(true);
        setHorizontalAlignment(SwingConstants.LEFT);
        setVerticalAlignment(CENTER);
        // setBorder( new LineBorder(Color.BLACK) );
    }

    public NSComboBoxRenderer(String expression) {
        this();
        this.expression = expression;
    }

    private Object ognlExpression;

    private Object getOgnlExpresion() {
        if (ognlExpression == null) {
            try {
                ognlExpression = Ognl.parseExpression(expression);
            } catch (OgnlException e) {
                throw new RuntimeException(e);
            }
        }

        return ognlExpression;
    }

    @Override
    public Component getListCellRendererComponent(//
            JList list,//
            Object value,//
            int index,//
            boolean isSelected,//
            boolean cellHasFocus) {

        if (isSelected) {
            setBackground(list.getSelectionBackground());
            setForeground(list.getSelectionForeground());
        } else {
            setBackground(list.getBackground());
            setForeground(list.getForeground());
        }

        if (value instanceof IIntegerIdentifier) {
            IIntegerIdentifier iden = (IIntegerIdentifier) value;
            setHorizontalAlignment(iden.getId() != null && iden.getId() == 0 ? SwingConstants.CENTER : SwingConstants.LEFT);
        }

        if (value == null || value instanceof String)
            this.setText((String) value);
        else {
            if (getExpression() != null && getOgnlExpresion() != null) {
                try {
                    this.setText("" + Ognl.getValue(getOgnlExpresion(), new OgnlContext(), value));
                } catch (OgnlException e) {
                    this.setText("<error>");
                    throw new RuntimeException(e);
                } catch (RuntimeException e) {
                    this.setText("<error>");
                    // throw e;
                }
            } else
                this.setText(value == null ? "<null>" : value.toString());
        }

        return this;

    }

    public String getExpression() {
        return expression;
    }

    public void setExpression(String expression) {
        this.expression = expression;
    }

}
